/*
 * Copyright 2016 Yonyou Auto Information Technology（Shanghai） Co., Ltd. All Rights Reserved.
 *
 * This software is published under the terms of the YONYOU Software
 * License version 1.0, a copy of which has been included with this
 * distribution in the LICENSE.txt file.
 *
 * @Project Name : JMC_APP
 *
 * @File name : TestUtil.java
 *
 * @Author : Administrator
 *
 * @Date : 2016年12月1日
 *
----------------------------------------------------------------------------------
 *     Date       Who       Version     Comments
 * 1. 2016年12月1日    Administrator    1.0
 *
 *
 *
 *
----------------------------------------------------------------------------------
 */

package org.marketing.common.util;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import org.apache.log4j.Logger;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

public class InternetImageTransUtil {
	private static Logger logger = Logger.getLogger(InternetImageTransUtil.class);
	public static String get64EncodeFromInternet(String url){
		HttpURLConnection httpConn = null;
		String encodeStr = "";
		try {
			// 从URL读取图片
			URL destUrl = new URL(url);
			httpConn = (HttpURLConnection) destUrl.openConnection();
			httpConn.connect();
			InputStream in = httpConn.getInputStream();
			encodeStr = changeStreamToEncodeStr(in);
		} catch (Exception e) {
			logger.error("get64EncodeFromInternet>>>>"+e.getMessage(),e);
		} finally {
			if (httpConn != null) {
				httpConn.disconnect();
			}
		}
		return encodeStr;
	}

	public static void main(String[] args) throws Exception {
		String url = "";// "http://10.180.8.247/fs01/20161130/087500610e1d868356232481144f599d.jpg";
		String path = "c:/0001.JPG";
		String encodeStr = get64EncodeFromInternet(url);
		generateImage2(encodeStr, path); // 将Base64字符转换为图片
	}

	/**
	 * 读取输入流,转换为Base64字符串
	 * 
	 * @param input
	 * @return
	 * @throws IOException
	 */
	@SuppressWarnings("restriction")
	public static String changeStreamToEncodeStr(InputStream input){
		byte[] data = null;
		try {
			// 读取图片字节数组
			ByteArrayOutputStream outStream = new ByteArrayOutputStream();
			byte[] buffer = new byte[1024];
			int len = 0;
			while ((len = input.read(buffer)) != -1) {
				outStream.write(buffer, 0, len);
			}
			data = outStream.toByteArray();
			input.close();
			outStream.close();
		} catch (Exception e) {
			logger.error("changeStreamToEncodeStr>>>>"+e.getMessage(),e);
		}
		// 对字节数组Base64编码
		BASE64Encoder encoder = new BASE64Encoder();
		return encoder.encode(data);// 返回Base64编码过的字节数组字符串
	}

	/**
	 * base64字符串转化成图片 对字节数组字符串进行Base64解码并生成图片
	 * 
	 * @param imgStr
	 *            数据内容(字符串)
	 * @param path
	 *            输出路径
	 * @return
	 */
	@SuppressWarnings("restriction")
	public static void generateImage2(String imgStr, String path) {
		BASE64Decoder decoder = new BASE64Decoder();
		try {
			byte[] b = decoder.decodeBuffer(imgStr);// Base64解码
			for (int i = 0; i < b.length; ++i) {
				if (b[i] < 0) {// 调整异常数据
					b[i] += 256;
				}
			}

			InputStream is = new ByteArrayInputStream(b);
			// 1K的数据缓冲
			byte[] bs = new byte[1024];
			// 读取到的数据长度
			int len;
			OutputStream os = new FileOutputStream(path);
			// 开始读取
			while ((len = is.read(bs)) != -1) {
				os.write(bs, 0, len);
			}
			// 完毕，关闭所有链接
			os.close();
			is.close();
		} catch (Exception e) {
			logger.error("generateImage2>>>>"+e.getMessage(),e);
		}
	}

	/**
	 * 
	 *
	 * @author sangdeliang @ description
	 * @date 2016年12月20日
	 * @param imgStreamStr
	 * @return
	 */
	@SuppressWarnings("restriction")
	public static byte[] generateImageBytes(String imgStreamStr) {
		BASE64Decoder decoder = new BASE64Decoder();
		try {
			byte[] b = decoder.decodeBuffer(imgStreamStr);// Base64解码
			for (int i = 0; i < b.length; ++i) {
				if (b[i] < 0) {// 调整异常数据
					b[i] += 256;
				}
			}
			return b;
		} catch (Exception e) {
			logger.error("generateImageBytes>>>>"+e.getMessage(),e);
			return new byte[0];
		}
	}
}
